<!-- src/components/admin/testitem-modal.vue -->
<template>
  <u-popup :show="T.showModal.value" mode="center" :round="10">
    <view class="vbox popup-container">
      <view class="popup-header">
        <text>{{
          T.modalMode.value === "edit" ? "编辑试题" : "添加试题"
        }}</text>
        <view class="fill"></view>
        <u-icon name="close" @click="T.closePopup()" size="18"></u-icon>
      </view>
      <u-form :model="T.currentModel" ref="formRef" :rules="rules" label-position="left">
        <u-form-item label="试题标题" prop="title">
          <u-input v-model="T.currentModel.title" placeholder="输入试题标题"></u-input>
        </u-form-item>

        <u-form-item label="试题类型" prop="type">
          <u-radio-group v-model="T.currentModel.type" placement="row">
            <u-radio label="单选" name="choice"></u-radio>
            <u-radio label="多选" name="mchoice"></u-radio>
            <u-radio label="判断" name="judge"></u-radio>
            <u-radio label="填空" name="blank"></u-radio>
          </u-radio-group>
        </u-form-item>

        <!-- 选择题选项 -->
        <u-form-item 
          v-if="['choice', 'mchoice'].includes(T.currentModel.type)" 
          label="选项内容" 
          prop="content"
        >
          <view class="options-container">
            <view 
              v-for="(option, index) in options" 
              :key="index" 
              class="option-item"
            >
              <view class="option-header">
                <text class="option-label">{{ getOptionLabel(index) }}.</text>
              </view>
              <u-input 
                v-model="options[index]" 
                placeholder="输入选项内容"
                class="option-input"
              />
              <u-button 
                v-if="options.length > 2" 
                type="error" 
                size="mini" 
                icon="close"
                @click="removeOption(index)"
                class="remove-btn"
              ></u-button>
            </view>
            <u-button 
              type="primary" 
              size="mini" 
              icon="plus"
              @click="addOption"
              class="add-option-btn"
            >添加选项</u-button>
          </view>
        </u-form-item>

        <!-- 判断题固定选项 -->
        <u-form-item 
          v-else-if="T.currentModel.type === 'judge'" 
          label="选项内容" 
          prop="content"
        >
          <view class="tf-options">
            <u-tag text="A. 正确" type="info" />
            <u-tag text="B. 错误" type="info" />
          </view>
        </u-form-item>

        <!-- 其他类型试题内容 -->
        <u-form-item 
          v-else 
          label="试题内容" 
          prop="content"
        >
          <u-input 
            v-model="T.currentModel.content" 
            placeholder="输入试题内容" 
            type="textarea"
            :auto-height="true"
          />
        </u-form-item>

        <!-- 答案 -->
        <u-form-item label="标准答案" prop="answer">
          <!-- 单选题 -->
          <u-radio-group 
            v-if="T.currentModel.type === 'choice'" 
            v-model="T.currentModel.answer" 
            placement="row"
          >
            <u-radio 
              v-for="(option, index) in getValidOptions()" 
              :key="index" 
              :label="getOptionLabel(index)" 
              :name="getOptionLabel(index)"
            ></u-radio>
          </u-radio-group>

          <!-- 多选题 -->
          <u-checkbox-group 
            v-else-if="T.currentModel.type === 'mchoice'" 
            v-model="T.currentModel.answer" 
            placement="row"
          >
            <u-checkbox 
              v-for="(option, index) in getValidOptions()" 
              :key="index" 
              :label="getOptionLabel(index)" 
              :name="getOptionLabel(index)"
            ></u-checkbox>
          </u-checkbox-group>

          <!-- 判断题 -->
          <u-radio-group 
            v-else-if="T.currentModel.type === 'judge'" 
            v-model="T.currentModel.answer" 
            placement="row"
          >
            <u-radio label="正确" name="t"></u-radio>
            <u-radio label="错误" name="f"></u-radio>
          </u-radio-group>

          <!-- 其他类型 -->
          <u-input 
            v-else 
            v-model="T.currentModel.answer" 
            placeholder="输入标准答案" 
            type="textarea"
            :auto-height="true"
          />
        </u-form-item>

        <u-form-item label="评分规则" prop="criteria">
          <u-input 
            v-model="T.currentModel.criteria" 
            placeholder="输入评分规则" 
            type="textarea"
            :auto-height="true"
          />
        </u-form-item>

        <view class="hbox">
          <u-button type="default" @click="T.closePopup()" text="取消"></u-button>
          <u-button type="primary" @click="handleSubmit" :text="T.modalMode.value === 'edit' ? '保存' : '添加'"></u-button>
        </view>
      </u-form>
    </view>
  </u-popup>
</template>

<script setup>
import { ref, watch } from "vue";
import T from "@/js/admin/testitem.js";

const formRef = ref();

// 选项数组（用于单选/多选题）
const options = ref([]);

// 添加选项
const addOption = () => {
  options.value.push('');
};

// 删除选项
const removeOption = (index) => {
  options.value.splice(index, 1);
  // 如果删除的是已选中的答案，也需要清除
  handleAnswerCleanup(index);
};

// 清理答案（当选项被删除时）
const handleAnswerCleanup = (index) => {
  const optionLabel = getOptionLabel(index);
  
  if (T.currentModel.type === 'choice' && T.currentModel.answer === optionLabel) {
    T.currentModel.answer = '';
  } else if (T.currentModel.type === 'mchoice' && Array.isArray(T.currentModel.answer) 
    && T.currentModel.answer.includes(optionLabel)) {
    const idx = T.currentModel.answer.indexOf(optionLabel);
    T.currentModel.answer.splice(idx, 1);
  }
};

// 获取选项标签（A, B, C, D...）
const getOptionLabel = (index) => {
  return String.fromCharCode(65 + index).toLowerCase();
};

// 获取有效选项（非空选项）
const getValidOptions = () => {
  return options.value.filter(opt => opt.trim() !== '');
};

// 监听试题类型变化
watch(
  () => T.currentModel.type,
  (newType) => {
    initializeOptions(newType);
    handleAnswerFormat(newType);
  },
  { immediate: true }
);

// 初始化选项
const initializeOptions = (type) => {
  if (['choice', 'mchoice'].includes(type)) {
    try {
      if (T.currentModel.content) {
        // 解析已有的选项内容
        const parsedContent = JSON.parse(T.currentModel.content);
        if (Array.isArray(parsedContent)) {
          options.value = parsedContent;
        } else {
          options.value = ['', ''];
        }
      } else {
        options.value = ['', ''];
      }
    } catch {
      options.value = ['', ''];
    }
  } else if (type === 'judge') {
    // 判断题使用固定选项
    options.value = [];
    T.currentModel.content = JSON.stringify(['正确', '错误']);
  } else {
    options.value = [];
  }
};

// 处理答案格式
const handleAnswerFormat = (type) => {
  if (type === 'mchoice') {
    // 确保多选题的答案是数组格式
    ensureArrayAnswer();
  } else {
    // 对于非多选题，如果答案是数组则转换为字符串
    if (Array.isArray(T.currentModel.answer)) {
      T.currentModel.answer = T.currentModel.answer.join(',');
    }
  }
};

// 确保多选题答案是数组格式
const ensureArrayAnswer = () => {
  if (!Array.isArray(T.currentModel.answer)) {
    // 如果答案是字符串，尝试解析或按逗号分割
    if (typeof T.currentModel.answer === 'string' && T.currentModel.answer) {
      try {
        T.currentModel.answer = JSON.parse(T.currentModel.answer);
      } catch (e) {
        T.currentModel.answer = T.currentModel.answer.split(',');
      }
    } else {
      T.currentModel.answer = [];
    }
  }
};

// 表单校验规则
const rules = ref({
  title: [
    { required: true, message: '请输入试题标题', trigger: ['blur', 'change'] }
  ],
  type: [
    { required: true, message: '请选择试题类型', trigger: ['blur', 'change'] }
  ],
  content: [
    { 
      required: true, 
      message: '请输入选项内容或试题内容', 
      trigger: ['blur', 'change'],
      validator: validateContent
    }
  ],
  answer: [
    { 
      required: true, 
      message: '请输入标准答案', 
      trigger: ['blur', 'change'],
      validator: validateAnswer
    }
  ]
});

// 校验内容
function validateContent(rule, value, callback) {
  if (['choice', 'mchoice'].includes(T.currentModel.type)) {
    if (options.value.filter(opt => opt.trim() !== '').length < 2) {
      callback(new Error('请至少添加两个选项'));
    } else {
      callback();
    }
  } else if (T.currentModel.type === 'judge') {
    callback(); // 固定选项，无需校验
  } else {
    if (!value || value.trim() === '') {
      callback(new Error('请输入试题内容'));
    } else {
      callback();
    }
  }
}

// 校验答案
function validateAnswer(rule, value, callback) {
  if (T.currentModel.type === 'choice' && (!value || value.trim() === '')) {
    callback(new Error('请选择答案'));
  } else if (T.currentModel.type === 'mchoice' && (!value || value.length === 0)) {
    callback(new Error('请选择答案'));
  } else if (T.currentModel.type === 'judge' && (!value || value.trim() === '')) {
    callback(new Error('请选择答案'));
  } else if (!value || value.trim() === '') {
    callback(new Error('请输入标准答案'));
  } else {
    callback();
  }
}

const handleSubmit = () => {
  // 在提交前处理选项内容
  prepareSubmitData();
  
  formRef.value.validate().then(() => {
    T.handleSubmit();
  }).catch(errors => {
    console.error('表单校验失败:', errors);
    uni.showToast({ title: '请检查输入内容', icon: 'none' });
  });
};

// 准备提交数据
const prepareSubmitData = () => {
  if (['choice', 'mchoice'].includes(T.currentModel.type)) {
    // 将选项数组转换为JSON字符串存储到content字段
    T.currentModel.content = JSON.stringify(options.value);
    
    // 处理多选题答案
    if (T.currentModel.type === 'mchoice' && Array.isArray(T.currentModel.answer)) {
      // 将数组答案转换为JSON字符串存储
      T.currentModel.answer = JSON.stringify(T.currentModel.answer);
    }
  } else if (T.currentModel.type === 'judge') {
    // 判断题使用固定选项
    T.currentModel.content = JSON.stringify(['正确', '错误']);
  }
};
</script>

<style scoped>
.popup-container {
  padding: 20px;
  width: 80vw;
  max-height: 80vh;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
}

.options-container {
  width: 100%;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 8px;
}

.option-header {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  background-color: #f5f5f5;
  border-radius: 4px;
  flex-shrink: 0;
}

.option-label {
  font-weight: bold;
  color: #666;
}

.option-input {
  flex: 1;
}

.remove-btn {
  width: 30px;
  height: 30px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-option-btn {
  margin-top: 10px;
}

.tf-options {
  display: flex;
  gap: 10px;
}

.hbox {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.hbox u-button {
  flex: 1;
}
</style>